<?php

include_once('simple_html_dom.php');
		
class SerialsChecker {

	private $html;
	private $html_obj;
	private $response_code = "error";
	
	const SUCCESS = "success";
	const ERROR = "error";

	function __construct() {
		$sock = fsockopen(HOST, 80, $errno, $errstr, 30);
		
		if ($sock)
		{
			fwrite($sock,  "GET / HTTP/1.0\n" .
					"Cookie: " . COOKIE . "\n" .
					"Host: " . HOST . "\n\n");
			$result = "";
			while (!feof($sock))
				$result .= fread($sock, 128);
			$this->html = $result;
			fclose($sock);
			$this->response_code = self::SUCCESS;
			
			$this->init_html_obj();
		} else {
			$this->response_code = self::ERROR;
		}
	}
	
	function get_response_code() {
		return $this->response_code;
	}
	
	private function init_html_obj() {
		$this->html_obj = str_get_html($this->html);
	}
	
	function get_episodes() {
		if ($this->response_code == $this->ERROR) {
			return NULL;
		}
		
		$episodes = array();
		
		$episodes_list  = array_reverse($this->html_obj->find('div[id=serialsLast] tr'));
		foreach ($episodes_list as $item) {
			$episode['serial_id'] = preg_replace('/.*=/', '', $item->children(1)->children(1)->getAttribute('href'));
			$episode['release_date'] = mysql_escape_string(trim($item->children(0)->innertext));
			$episode['number'] = mysql_escape_string(trim($item->children(2)->innertext));
			$episode['caption'] = mysql_escape_string(trim($item->children(3)->innertext));
			$episode['released'] = 1;
			
			$episodes[] = $episode;
		}
		
		$episodes_list  = $this->html_obj->find('div[id=serialsAll] tr');
		foreach ($episodes_list as $item) {
			$episode['serial_id'] = preg_replace('/.*=/', '', $item->children(1)->children(1)->getAttribute('href'));
			$episode['release_date'] = mysql_escape_string(trim($item->children(0)->innertext));
			$episode['number'] = mysql_escape_string(trim($item->children(2)->innertext));
			$episode['caption'] = mysql_escape_string(trim($item->children(3)->innertext));
			$episode['released'] = 0;
			
			$episodes[] = $episode;
		}
		
		return $episodes;
	}
	
	function get_serials() {
		if ($this->response_code == $this->ERROR) {
			return NULL;
		}
	
		$serials_list = $this->html_obj->find("table div.serialcheck");
		
		$serials = array();
		
		foreach($serials_list as $item) {
			$serial['id'] = preg_replace('/.*=/', '', $item->children(1)->getAttribute('href'));
			$serial['link'] = mysql_escape_string(PROTOCOL . HOST . $item->children(1)->getAttribute("href"));
			$serial['caption'] = mysql_escape_string(trim($item->children(1)->innertext));
			$serial['img_small'] = mysql_escape_string(PROTOCOL . HOST . "/files/16_$serial[id].jpg");
			$serial['img_big'] = mysql_escape_string(PROTOCOL . HOST . "/files/$serial[id].jpg");
			
			$serials[] = $serial;
		}
		
		return $serials;
	}
}

?>